$NG.AllReady(function (page, { useDataIndexChange, useValuesChange, useClick, useUpdateRows }) {
    if (page.oType == "add") {
        getGzZc()
        cntMFilter()

    }
    const mstform = $NG.getCmpApi("p_form_sub_cnt_m");
    const dgrid1 = $NG.getCmpApi("p_form_sub_cnt_d1");
    const dgrid2 = $NG.getCmpApi("p_form_sub_cnt_d2");
    const gridToolbar = $NG.getCmpApi("toolbar_p_form_sub_cnt_d1")
    gridToolbar.getItem('imp').setProps({ children: '引用完工上报清单明细' })
    const gridToolbar1 = $NG.getCmpApi("toolbar_p_form_sub_cnt_d2")
    gridToolbar1.getItem('imp').setProps({ children: '引用分包奖罚单明细' })
    try{
        console.log(`执行力`,);
        $NG.updateUI((updater)=>{
            updater.editbar.p_form_sub_cnt_d1.imp.setProps({
                hidden:true
            })
        })
    }catch(e){
        console.log(`没找到单据引用按钮`,e);
    }
    useValuesChange(({ args }) => {
        console.log(`监听合同变化`, args);
        const _data = args[0]
        cntMFilter()
        getCntMInfoByPhid()
        //getPtInfoByPhid_cnt()
        getCntDetil()
        getFbjsAmt()
        getFbCntJsInfo()
    }, "p_form_sub_cnt_m.u_cnt_name")

    useValuesChange(({ args }) => {
        cntMFilter()
        getCntDetil()
    }, "p_form_sub_cnt_m.phid_pc")

    useValuesChange(({ args }) => {
        getCntDetil()
        hideDgridKey()
    }, "p_form_sub_cnt_m.u_js_type")
    useUpdateRows(({ args }) => {
        sumAmt()
    }, "p_form_sub_cnt_d1")
    useUpdateRows(({ args }) => {
        sumAmt()
    }, "p_form_sub_cnt_d2")

    useDataIndexChange(({ args }) => {
        args[0].u_bqhd_qty = args[0].u_bqjl_qty
        sumAmt()
        console.log(`计量数量监听`, args[0]);
        dgrid1.refreshView()
    }, "u_bqjl_qty")

    function sumAmt() {
        const arr1 = dgrid1.getRows()
        const arr2 = dgrid2.getRows()

        arr1.forEach((item, index) => {
            if ((Number(item.u_bqhd_qty) || 0) > (Number(item.u_bqjl_qty) || 0)) {
                $NG.alert("当前本期核定数量大于本期计量数量，请重新填写")
                item.u_bqhd_qty = 0
            }
            // 本期核定数量
            console.log(!window.__cache_lsz_d1[item.u_cnt_qd_name] || !item.u_cnt_qd_name);
            if (!window.__cache_lsz_d1[item.u_cnt_qd_name] || !item.u_cnt_qd_name || !window.__cache_lsz_d1_qty[item.u_cnt_qd_name]) {
                getFbCntJs(item.u_cnt_qd_name, (amt, qty) => {
                    window.__cache_lsz_d1[item.u_cnt_qd_name] = amt
                    window.__cache_lsz_d1_qty[item.u_cnt_qd_name] = qty
                    item.u_bq_hjqty = ((Number(item.u_bqjl_qty) || 0) - (Number(item.u_bqhd_qty)) || 0)
                    item.u_ljhd_qty = ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0)) < 0 ? 0 : ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0))
                    item.u_bqjs_amt_vat = (Number(item.u_cnt_prc_vat) || 0) * (Number(item.u_bqhd_qty) || 0)
                    item.u_ljjs_amt_vat = Number(amt) + Number(item.u_bqjs_amt_vat)
                    item.u_lj_hjqty = Number(qty) + Number(item.u_bqhd_qty)
                })
            } else {
                item.u_bq_hjqty = ((Number(item.u_bqjl_qty) || 0) - (Number(item.u_bqhd_qty)) || 0)
                item.u_ljhd_qty = ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0)) < 0 ? 0 : ((Number(item.u_ljjl_qty) || 0) - (Number(item.u_lj_hjqty) || 0))
                item.u_bqjs_amt_vat = (Number(item.u_cnt_prc_vat) || 0) * (Number(item.u_bqhd_qty) || 0)
                item.u_ljjs_amt_vat = (Number(window.__cache_lsz_d1[item.u_cnt_qd_name]) || 0) + (Number(item.u_bqjs_amt_vat) || 0)
                item.u_lj_hjqty = (Number(window.__cache_lsz_d1_qty[item.u_cnt_qd_name]) || 0) + (Number(item.u_bqhd_qty) || 0)
            }
            //税额
            item.u_tax_amt = ((Number(item.u_cnt_prc_vat) || 0) - (Number(item.u_cnt_prc) || 0)) * (Number(item.u_bqhd_qty) || 0)
        })

        //计算合同结算金额
        let cnt_amt = arr1.reduce((value, item) => {
            value += (Number(item.u_bqjs_amt_vat) || 0)
            return value
        }, 0)
        //计算合同结算金额（包含奖罚单）

        let cnt_amt_in_jf = arr2.reduce((value, item) => {
            if (item.u_jf_lx == '2') {
                value += (Number(item.u_amt_vat) || 0)
            } else {
                value -= (Number(item.u_amt_vat) || 0)
            }
            return value
        }, 0)

        $NG.updateState((updater) => {
            updater.data.p_form_sub_cnt_m.setProps({
                u_jsamt_vat: cnt_amt,
                u_jsamt_total: cnt_amt - cnt_amt_in_jf,
                u_ljjsze: window._catch_cnt_js_amt + (cnt_amt - cnt_amt_in_jf)
            })
        })
        dgrid1.refreshView()
    }
    //获取累计合同结算金额
    getFbjsAmt()
    function getFbjsAmt() {
        if (!mstform.getItem("u_cnt_name").getValue()) return
        const u_cnt_name = mstform.getItem("u_cnt_name").getValue()
        $NG.execServer("getFbjsAmt", { u_cnt_name }, (res) => {
            console.log(`获取累计`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_sub_cnt_m.setProps({
                    u_ljjs_amt: _data.amt,
                    u_ljjsze: _data.total_amt
                })
            })
        })
    }

    //结算清单相关计算
    window.__cache_lsz_d1 = {}
    window.__cache_lsz_d1_qty = {}
    //获取项目信息
    function getProjectInfo() {
        $NG.execServer(
            "getPtInfoByPhid_cnt",
            { phid_cnt: mstform.getItem("u_cnt").getValue() },
            function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                $NG.updateState((updater) => {
                    updater.data.当前表名.setProps({
                        //项目编码
                        pc_no: datas.pc_no,
                        //项目金额
                        approx_contract_fc: datas.approx_contract_fc,
                        //计划开工日期
                        start_date: datas.start_date,
                        //计划完工日期
                        end_date: datas.end_date,
                        //售前顾问
                        u_sqgw: {
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        //项目经理
                        u_project_manager: {
                            value: datas.project_manager_phid,
                            label: datas.project_manager_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                        //组织
                        phid_org_phid: {
                            value: datas.phid_org_phid,
                            label: datas.phid_org_name,
                        },
                        //区域中心
                        u_regional_center: {
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        },
                        //产品线
                        user_product_line: {
                            value: datas.midwife_phid,
                            label: datas.midwife_name,
                        },
                        //客户名称
                        customer: {
                            value: datas.customer_id,
                            label: datas.customer_name,
                        },
                        //部门
                        u_dept: {
                            value: datas.dept_phid,
                            label: datas.dept_name,
                        },
                        //项目类型
                        u_pc_type: {
                            value: datas.type_phid,
                            label: datas.type_name,
                        },
                        //项目预算组织编码
                        budget_org_code: datas.budget_org_no,
                        //项目预算组织
                        budget_org_phid: {
                            value: datas.budget_org_phid,
                            label: datas.budget_org_name,
                        },
                    });
                });
            }
        );
    }
    //获取结算明细
    function getFbCntJs(phid, fun) {
        if (!phid || !mstform.getItem("u_cnt_name").getValue()) { fun(0); return }
        $NG.execServer("getFbCntJs", { cnt_phid: mstform.getItem("u_cnt_name").getValue(), qd_phid: phid }, function (res) {
            console.log(`获取累计金额`, mstform.getItem("u_cnt_name").getValue(), phid, res);
            if (res.count == 0) {
                fun(0, 0)
            } else {
                const _data = JSON.parse(res.data)[0].extendObjects
                fun(_data.total_amt, _data.total_qty)
            }
            dgrid1.refreshView()
        })
    }

    //获取合同信息
    getCntMInfoByPhid()
    function getCntMInfoByPhid() {
        if (!mstform.getItem("u_cnt_name").getValue()) return
        console.log(`开始获取合同`);
        $NG.execServer(
            "getCntMInfoByPhid",
            { phid: mstform.getItem("u_cnt_name").getValue() },
            function (res) {
                if (res.count == 0) return
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(datas);
                $NG.updateState((updater) => {
                    updater.data.p_form_sub_cnt_m.setProps({
                        u_cnt_no: datas.pcm_no, //合同编码
                        u_fbht_amt: datas.cnt_sum_vat_fc, //合同价税合计
                        //合同类型
                        pct_id: { value: datas.pct_id, label: datas.pct_name },
                        //甲方单位
                        u_dept_a: {
                            value: datas.customer_id,
                            label: datas.customer_name,
                        },
                        //乙方单位
                        u_yf_dept: {
                            value: datas.supply_id,
                            label: datas.supply_name,
                        },
                    });
                });
            }
        );
    }

    //获取工作周期
    function getGzZc() {
        let _count = {}
        $NG.execServer("getInDate", {}, function (res) {
            console.log(`获取工作周期`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_sub_cnt_m.setProps({
                    phid_cycle: {
                        label: _data.bill_name,
                        value: _data.phid
                    }
                })
            })
        })
    }
    // 计算2个日期之间得天数
    function formatDate(dateStr, outputFormat) {
        const date = new Date(dateStr);

        if (isNaN(date)) {
            return "无效的日期字符串";
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");

        let formattedDate;

        switch (outputFormat) {
            case "yyyy-mm-dd":
                formattedDate = `${year}-${month}-${day}`;
                break;
            case "yyyy-mm-dd HH:mm":
                formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
                break;
            // 可以根据需要继续添加其他格式的处理逻辑
            default:
                formattedDate = "不支持的输出格式";
        }

        return formattedDate;
    }
    async function getCntDetil() {
        // 感觉没用，禁用
        console.log(mstform.getItem("u_js_type").getValue());
        // console.log(,mstform.getItem("u_js_type").getValue());
        if (!mstform.getItem("u_js_type").getValue() || !(mstform.getItem("u_js_type").getValue() == '2') || !mstform.getItem("u_cnt_name").getValue()) return
        await $NG.execServer("getCntDetail", { phid: mstform.getItem("u_cnt_name").getValue() }, async function (res) {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)
            console.log(`明细`, datas);
            await getFbCntJSSbqdQty()
            dgrid1.clearRows().then(() => {
                let _arr = []
                _arr = []
                datas.forEach(items => {
                    const item = items.extendObjects
                    let qty = 0
                    window._catch_sbqdqty.filter(el => {
                        if(el.u_sbqd_name == item.u_sbqd_name){
                            qty = el.qty
                        }
                    })
                    _arr.push({
                        u_sbqd_no: item.user_u_equipment_list_no,
                        u_sbqd_name: item.user_u_equipment_list_name,
                        u_sbqd_name_EXName: item.user_u_equipment_list_name_exname,
                        itemid: item.phid_itemid,
                        itemno_EXName: item.itemno,
                        itemname: item.itemname,
                        u_cnt_qd_name: item.phid,
                        u_cnt_qd_name_EXName: item.item_name,
                        u_cnt_qd_no: item.item_no,
                        u_bqjl_qty: item.qty,
                        u_bqhd_qty:item.qty,
                        u_yjs_qty:qty,
                        u_cnt_prc: item.prc_fc,
                        u_cnt_qty:item.qty,
                        u_cnt_prc_vat: item.prc_vat_fc,
                        u_bqjs_amt_vat: item.amt,
                        u_tax: item.taxrate,
                        u_tax_amt: item.taxamt

                    })
                })
                dgrid1.addRows(_arr)
                dgrid1.refreshView()
            })
        })
    }
    //获取项目信息
    function getPtInfoByPhid_cnt() {
        $NG.execServer("getPtInfoByPhid_cnt", { phid_cnt: mstform.getItem("u_cnt_name").getValue() }, (res) => {
            console.log(`获取项目信息`, res);
            if (res.count === 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            console.log(datas);
            $NG.updateState((updater) => {
                updater.data.p_form_sub_cnt_m.setProps({
                    phid_pc: {
                        value: datas.pc_phid,
                        label: datas.pc_name
                    }
                })
            })
        })
    }

    // 表体部分字段隐藏
    hideDgridKey()
    function hideDgridKey() {
        const _arr = ['u_bqjl_qty', 'u_bqhd_qty', 'u_bq_hjqty', 'u_lj_hjqty']
        console.log(`结算类型`, mstform.getItem("u_js_type").getValue());
        if (mstform.getItem("u_js_type").getValue() == '2') {
            _arr.forEach((item) => {
                $NG.updateUI((updater) => {
                    // console.log(`hiden`,updater.editGrid.p_form_sub_cnt_d1[item]);
                    // if (updater.editGrid.p_form_sub_cnt_d1[item]) {
                        updater.editGrid.p_form_sub_cnt_d1[item].setProps({
                            hidden: true
                        })
                    // }
                })
            })
        } else {
            _arr.forEach((item) => {
                $NG.updateUI((updater) => {
                    // if (updater.editGrid.p_form_sub_cnt_d1[item]) {
                        updater.editGrid.p_form_sub_cnt_d1[item].setProps({
                            hidden: false
                        })
                    // }
                })
            })
        }
    }
    // 获取合同累计含奖罚单结算金额
    getFbCntJsInfo()
    function getFbCntJsInfo() {
        window._catch_cnt_js_amt = 0
        const cnt = mstform.getItem("u_cnt_name").getValue()
        if (!cnt) return
        $NG.execServer("getFbCntJsInfo", { cnt }, (res) => {
            console.log(`获取合同累计结算信息`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            window._catch_cnt_js_amt = (Number(_data.total_cntamt) || 0)
        })
    }

    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            console.log("过滤参数检查", updater);
            updater.fieldSetForm.p_form_sub_cnt_m.u_cnt_name.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi("p_form_sub_cnt_m").getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi("p_form_sub_cnt_m").getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        'pcm3_cnt_m.phid_pc': $NG.getCmpApi("p_form_sub_cnt_m").getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }

    // 获取设备清单已结算数量
    getFbCntJSSbqdQty()
    async function getFbCntJSSbqdQty(){
        window._catch_sbqdqty = []
        const cnt = mstform.getItem("u_cnt_name").getValue()
        if(!cnt) return 
        await $NG.execServer("getFbCntJSSbqdQty",{cnt},function(res){
            console.log(`获取设备清单项目`,res);
            if(res.count == 0) return 
            window._catch_sbqdqty = JSON.parse(res.data).reduce((value,item)=>{
                value.push({
                    ...item.extendObjects
                })
                return value
            },[])
        })
    }
});

